<?php

namespace App\Http\Controllers\DingAttendance;

use App\Http\Controllers\Controller;
use App\Models\Attendance\AttendanceData;
use App\Models\Role;
use App\Models\Dict;
use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DingAttendanceController extends Controller
{
    public $roleId;
    public $roleName;
    public $userId;
    public $userName;

    public function getSeeIds($userId): void
    {
        if ($userId) {
            $userInfo = User::query()->where('ding_user_id', $userId)->first();
            if ($userInfo) {
                $this->roleId = $userInfo['group_id'];
                $roleId = DB::table('sys_roles_users')->where('user_id', $userInfo['id'])->pluck('role_id')->toArray();
                $this->roleName = Role::query()->whereIn('id', $roleId)->pluck('name')->toArray();
                $this->userId = $userInfo['id'];
                $this->userName = $userInfo['name'];
            }
        }
    }
    /**
     * 获取车队长上报类型
     *
     * @return void
     */
    public function getReportType()
    {
        $data = Dict::getOptionsByName('车队长上报类型');
        $result = [];
        foreach ($data as $k => $v) {
            $result[$k]['label'] = $v['title'];
            $result[$k]['value'] = $v['value'];
        }
        return response()->formatJson($result);
    }

    /**
     * 掉趟列表
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function attendanceList(Request $request)
    {
        $params = $request->all();
        $this->getSeeIds($params['ding_user_id']);

        if ($params['date'][0] === null && $params['date'][1] === null) {
            $params['date'] = [];
        } else {
            $date = $params['date'];
            $params['date'] = [
                date('Y-m-d', strtotime($date[0])),
                date('Y-m-d', strtotime($date[1])),
            ];
        }
        $data = $this->getAttendanceList($params)->orderByDesc('date')->get()->toArray();

        $data = collect($data)->groupBy('created_at')->toArray();

        $data = $this->transData($data);

        return response()->formatJson($data);
    }

    public function getAttendanceList($params): Builder
    {
        $query = AttendanceData::query();

        if (isset($params['busNumber'])) {
            $query->where('busNumber', 'like', '%' . $params['busNumber'] . '%');
        }

        if ($params['date']) {
            $query->whereBetween('date', [$params['date']]);
        }

        if (isset($params['page_number'], $params['page_size'])) {
            $query
                ->limit($params['page_size'])
                ->offset(($params['page_number'] - 1) * $params['page_size']);
        }

        return $query->where('user_id', $this->userId);
    }

    public function transData($params)
    {
        $data = [];
        foreach ($params as $dateTime => $items) {
            $detail = [];
            foreach ($items as $item) {
                $detail[] = [
                    'id'        => $item['id'],
                    'name'      => $item['name'],
                    'busNumber' => $item['busNumber'],
                    'type'      => $item['type'],
                ];
            }
            $data[] = [
                'date'       => $items[0]['date'],
                'detail'     => $detail,
                'created_at' => $dateTime,
            ];
        }

        return $data;
    }

    /**
     * 保存车队长上报
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function storeAttendance(Request $request)
    {
        $params = $request->all();
        $params['date'] = date('Y-m-d', strtotime($params['date']));
        $this->getSeeIds($params['ding_user_id']);
        $insertData = [];
        $dateTime = date('Y-m-d H:i:s');
        if (isset($params['detail'])) {
            foreach ($params['detail'] as  $v) {
                //处理类型
                switch (mb_substr($v['type'], 0, 2)) {
                    case '半天':
                        $v['duration'] = '0.5';
                        break;
                    case '全天':
                        $v['duration'] = '1';
                        break;
                    default:
                        $v['duration'] = '1';
                        break;
                }
                //处理上报的车牌号,将其中字母转化为大写
                $v['busNumber'] = strtoupper($v['busNumber']);
                //处理线路
                if (isset($v['line'])) {
                    $v['line'] = str_replace('路', '', $v['line']);
                } else {
                    //获取当前查询月份车辆线路分布
                    $v['line'] = DB::table('akbus_bus_distribution')
                        ->where('license_plate_num', 'like',$v['busNumber'].'%')
                        ->where('date', '<=', $params['date'])
                        ->where('end_date', '>=', $params['date'])
                        ->value('line');
                }
                //判断是否已经添加此条数据
                $v['date'] = $params['date'];
                $id = DB::table('akbus_attendance_data')->where($v)->value('id');
                if ($id) {
                    continue;
                }
                $insertData[] = [
                    'date'       => $params['date'],
                    'name'       => $v['name'],
                    'busNumber'  => $v['busNumber'],
                    'type'       => $v['type'],
                    'line'       => $v['line'] ?: '',
                    'duration'   => $v['duration'],
                    'user_id'    => $this->userId,
                    'created_at' => $dateTime,
                ];
                //判断是否需要同步考勤汇总的数据
                if ($params['date'] < date('Y-m-d')) {
                    //上报数据不是当天的,需要汇总                    
                    $updateData = [];
                    switch ($v['type']) {
                        case '半天修车':
                            $updateData['fixTime'] = 0.5;
                            break;
                        case '半天请假':
                            $updateData['leaveTime'] = 0.5;
                            break;
                        case '半天停运':
                            $updateData['stopTime'] = 0.5;
                            break;
                        case '半天检气瓶':
                            $updateData['checkGas'] = 0.5;
                            break;
                        case '全天修车':
                            $updateData['fixTime'] = 1;
                            break;
                        case '全天请假':
                            $updateData['leaveTime'] = 1;
                            break;
                        case '全天停运':
                            $updateData['stopTime'] = 1;
                            break;
                        case '全天检气瓶':
                            $updateData['checkGas'] = 1;
                            break;
                        default:
                            break;
                    };
                    $this->harmonizeCollect($updateData, $v);
                }
            }
        }
        $result = AttendanceData::query()->insert($insertData);
        $message = $result ? '添加成功' : '添加失败';

        return response()->formatJson($result, $message);
    }
    public function deleteAttendance(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = $request['ids'];
            foreach ($ids as  $id) {
                $attendanceData = AttendanceData::query()->find($id)->toArray();
                if ($attendanceData['date'] < date('Y-m-d')) {
                    //需要同步考勤汇总记录
                    //处理类型
                    $updateData = [];
                    switch ($attendanceData['type']) {
                        case '半天修车':
                        case '全天修车':
                            $updateData['fixTime'] = 0;
                            break;
                        case '半天请假':
                        case '全天请假':
                            $updateData['leaveTime'] = 0;
                            break;
                        case '半天停运':
                        case '全天停运':
                            $updateData['stopTime'] = 0;
                            break;
                        case '半天检气瓶':
                        case '全天检气瓶':
                            $updateData['checkGas'] = 0;
                            break;
                        default:
                            break;
                    }
                    $this->harmonizeCollect($updateData, $attendanceData);
                }
            }
            $delCount = AttendanceData::destroy($ids);
            $result = $delCount !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }
    /**
     * 同步车队长上报数据到考勤汇总
     *
     * @param  $updateData 修改的数据
     * @param  $params
     * @return void
     */
    public function harmonizeCollect($updateData, $params)
    {
        $bus_collect_id = DB::table('akbus_bus_attendance_collect')
            ->where('signDate', $params['date'])
            ->where('busNumber', $params['busNumber'])
            ->where('is_del', 0)
            ->value('id');
        if ($bus_collect_id) {
            DB::table('akbus_bus_attendance_collect')
                ->where('id', $bus_collect_id)
                ->update($updateData);
        } else {
            //无相应数据判断是否添加
            if ($params['busNumber'] != '无' && $params['busNumber'] != '') {
                $busInsertData = $updateData;
                $busInsertData['signDate'] = $params['date'];
                $busInsertData['busNumber'] = $params['busNumber'];
                $busInsertData['line'] = $params['line'];
                $busInsertData['created_at'] = date('Y-m-d H:i:s');
                DB::table('akbus_bus_attendance_collect')->insert($busInsertData);
            }
        }
        $driver_collect_id = DB::table('akbus_driver_attendance_collect')
            ->where('signDate', $params['date'])
            ->where('driver', $params['name'])
            ->where('is_del', 0)
            ->value('id');
        if ($driver_collect_id) {
            DB::table('akbus_driver_attendance_collect')
                ->where('id', $driver_collect_id)
                ->update($updateData);
        } else {
            //无相应数据判断是否添加
            if ($params['name'] != '无' && $params['name'] != '') {
                $driverInsertData = $updateData;
                $driverInsertData['signDate'] = $params['date'];
                $driverInsertData['driver'] = $params['name'];
                $driverInsertData['line'] = $params['line'];
                $driverInsertData['created_at'] = date('Y-m-d H:i:s');
                DB::table('akbus_driver_attendance_collect')->insert($driverInsertData);
            }
        }
    }
}
